﻿using MvcDemo.Models;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace MvcDemo.Controllers
{
    public class RedisTestController : Controller
    {
        //第一种创建客户端方式：
        //RedisClient client = new RedisClient("127.0.0.1", 6379);
        //第二种创建客户端方式：同时写入两台服务器
        public static IRedisClientsManager clientManager = new PooledRedisClientManager(new string[] {"192.168.10.240:6379"});
        public static IRedisClient client = clientManager.GetClient();




        // GET: RedsTest
        public ActionResult Index()
        {

            //在Redis中存储常用的5种数据类型：String,Hash,List,SetSorted set
            //参考：https://www.cnblogs.com/caokai520/p/4409712.html
            client.FlushAll();

            //string类型
            //RedisString();

            //hash类型
            RedisHash();

            //List示例
            //RedisList();

            //set 无序集合
            //Set();

            //SetSorted 有序集合
            //SetSorted();

            return View();
        }


        #region String       
        private void RedisString()
        {

            client.Add<string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(30000));
            string RedisFirstStr = client.Get<string>("StringValueTime");
            ViewData["String1"] = client.Get<string>("StringValueTime");

            var user = new User() { Id = 001, Name = "第一次"+DateTime.Now.ToString() };

            client.Add<User>("StringEntity", user);
            User Get_User = client.Get<User>("StringEntity");
            ViewData["String2"] = string.Format("数据类型为：String.键:StringEntity,值:{0} {1}", Get_User.Id, Get_User.Name);
        }

        #endregion

        #region Hash

        private void RedisHash()
        {
            client.SetEntryInHash("HashID", "Name", "张三");
            client.SetEntryInHash("HashID", "Age", "24");
            client.SetEntryInHash("HashID", "Sex", "男");
            client.SetEntryInHash("HashID", "Address", "上海市XX号XX室"+DateTime.Now.ToString());
            client.SetEntryInHash("HashID-2", "Address2", "上海市XX号XX室2"+DateTime.Now.ToString());

            string dateString = DateTime.Now.ToString();
            for (int i = 0; i < 100; i++)
            {
                string hashStr = "StuID"+i+DateTime.Now.ToString("yyyyMMddHHmmssfff");
                client.SetEntryInHash(hashStr, "Name", "张三" + i);
                client.SetEntryInHash(hashStr, "Age", "24");
                client.SetEntryInHash(hashStr, "Sex", "男");
                client.SetEntryInHash(hashStr, "Address", "上海市XX号" + i + "室");
                client.SetEntryInHash(hashStr, "CreateDate", DateTime.Now.ToString());

                List<string> HaskValues = client.GetHashValues(hashStr);
                ViewData[hashStr] = HaskValues;
            }


            List<string> HaskKey = client.GetHashKeys("HashID");
            //获取hash Key
            //ViewData["HaskKey"] = HaskKey;

            List<string> HaskValue = client.GetHashValues("HashID");
            //获取HaskValue
            //ViewData["HaskValue"] = HaskValue;

            List<string> AllKey = client.GetAllKeys(); //获取所有的key（含所有类型）
            ViewData["AllKey"] = AllKey;

        
        }
        #endregion

        #region List
        private void RedisList()
        {
            /*
           * list是一个链表结构，主要功能是push,pop,获取一个范围的所有的值等，操作中key理解为链表名字。 
           * Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素，
           * 这样list既可以作为栈，又可以作为队列。Redis list的实现为一个双向链表，即可以支持反向查找和遍历，更方便操作，不过带来了部分额外的内存开销，
           * Redis内部的很多实现，包括发送缓冲队列等也都是用的这个数据结构 
           */
            client.EnqueueItemOnList("QueueListId", "1.张三");  //入队
            client.EnqueueItemOnList("QueueListId", "2.张四");
            client.EnqueueItemOnList("QueueListId", "3.王五");
            client.EnqueueItemOnList("QueueListId", "4.王麻子");
            string dateString = DateTime.Now.ToString();
            for (int i = 0; i < 100; i++)
            {
                client.EnqueueItemOnList("QueueListId", "学号"+i+",时间："+ dateString);
            }
 
            int q = client.GetListCount("QueueListId");
            List<string> qList = new List<string>();
            for (int i = 0; i < q; i++)
            {
                qList.Add(client.DequeueItemFromList("QueueListId"));
            }


            ViewData["qList"] = qList;

            client.PushItemToList("StackListId", "1.张三");  //入栈
            client.PushItemToList("StackListId", "2.张四");
            client.PushItemToList("StackListId", "3.王五");
            client.PushItemToList("StackListId", "4.王麻子");
            int p = client.GetListCount("StackListId");
            List<string> pList = new List<string>();
            for (int i = 0; i < p; i++)
            {
                pList.Add(client.PopItemFromList("StackListId"));
            }
            ViewData["pList"] = pList;

        }
        #endregion

        #region Set无序集合
        private void Set()
        {
            /*
            它是string类型的无序集合。set是通过hash table实现的，添加，删除和查找,对集合我们可以取并集，交集，差集
            */
            client.AddItemToSet("Set1001", "小A");
            client.AddItemToSet("Set1001", "小B");
            client.AddItemToSet("Set1001", "小C");
            client.AddItemToSet("Set1001", "小D");
            HashSet<string> hashsetA = client.GetAllItemsFromSet("Set1001");
            ViewData["hashsetA"] = hashsetA;

            client.AddItemToSet("Set1002", "小K");
            client.AddItemToSet("Set1002", "小C");
            client.AddItemToSet("Set1002", "小A");
            client.AddItemToSet("Set1002", "小J");
            HashSet<string> hashsetB = client.GetAllItemsFromSet("Set1002");
            ViewData["hashsetB"] = hashsetB;

            //并集
            HashSet<string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
            ViewData["hashUnion"] = hashUnion;
            //交集
            HashSet<string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
            ViewData["hashG"] = hashG;
            //[返回存在于第一个集合，但是不存在于其他集合的数据。差集]
            HashSet<string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });
            ViewData["hashD"] = hashD;
        }

        #endregion

        #region  SetSorted 有序集合     
        /*      sorted set 是set的一个升级版本，它在set的基础上增加了一个顺序的属性，这一属性在添加修改.元素的时候可以指定，      
          每次指定后，zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表，一列存 value,一列存顺序。操作中key理解为zset的名字.      */
        private void SetSorted()
        {
            client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
            client.AddItemToSortedSet("SetSorted1001", "2.星仔");
            client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
            List<string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
            ViewData["listSetSorted"] = listSetSorted;
        }
        #endregion


    }
}